package mygang.controller.manager;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mygang.controller.AbstractController;
import mygang.helper.JsonHelper;
import mygang.helper.Utils;
import mygang.model.constructor.field.FieldTemplate;
import mygang.model.constructor.field.Element;
import mygang.service.manager.ElementService;
import mygang.service.manager.FieldTemplateService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 * date: 29/10/2012
 */
@Controller
@RequestMapping(AbstractController.MANAGE_TEMPLATE)
public class FieldTemplateController extends AbstractManageController<FieldTemplateService, FieldTemplate> {
    
    protected Logger log = Logger.getLogger(FieldTemplateController.class);
    @Autowired
    private ElementService elementService;

    @RequestMapping(value = "/getElements", method = RequestMethod.POST)
    public void getElements(HttpServletResponse response) throws IOException {
        JsonHelper.prepareJsonResponse(Utils.convertToOptions(elementService.getAll()), response);
    }
    
    public FieldTemplate prepareObject(HttpServletRequest request) throws Exception {
        Long id = getLong(request, "id");
        
        String name = request.getParameter("name");
        if(name==null || name.isEmpty()) throw new Exception("Name is not specified");
        
        Long elementId = getLong(request, "elementId");
        if(elementId==null) throw new Exception("UI element is not selected");
        Element element = elementService.getById(elementId.longValue());
        
        String regex = request.getParameter("regex");
        String mask = request.getParameter("mask");
        boolean isActive = getBoolean(request, "active");
        
        return id==null ? new FieldTemplate(name, element, regex, mask, isActive) : new FieldTemplate(id.longValue() ,name, element, regex, mask, isActive) ;
    }

    String getLink() {
        return MANAGE_TEMPLATE;
    }
}